#!/usr/bin/env python

import os
import re
import sys
import bsddb
import gzip
from subprocess import check_call

LOCUS_RE = re.compile(r"LOCUS\s+(\w+)\s+.*")

def parse_locus(s):
    m = LOCUS_RE.match(s)
    if m:
        return m.groups()[0]
    else:
        return None

if __name__ == "__main__":
 
    input_files_fname = sys.argv[1]
    output_dirname = sys.argv[2]

    cnt_all = 0
    cnt_success = 0
    for fname in open(input_files_fname):
        cnt_all += 1
        input_fname = fname.strip()
        f = open(input_fname)
        locus = parse_locus(f.readline())
        f.close()
        if not locus:
            print >> sys.stderr, 'Cannot parse locus from ', input_fname
            continue
        
        out_fname = os.path.join(output_dirname, locus)
        if os.path.exists(out_fname):
            print >> sys.stderr, 'Locus already exists: %s' % locus
            continue
        
        check_call("cat %s | gzip > %s" % (input_fname, out_fname), shell=True)
        cnt_success += 1

    print "Done! (%s/%s)" % (cnt_success, cnt_all)

